#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
翻译API服务启动和测试脚本
"""

import subprocess
import time
import requests
import json
import sys
import os
from pathlib import Path

def check_dependencies():
    """检查依赖是否安装"""
    try:
        import fastapi
        import uvicorn 
        import transformers
        import torch
        print("✅ 所有依赖已安装")
        return True
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("请运行: pip install fastapi uvicorn transformers torch pydantic")
        return False

def start_api_server():
    """启动翻译API服务"""
    print("🚀 启动翻译API服务...")
    script_dir = Path(__file__).parent
    api_script = script_dir / "translation_api.py"
    
    if not api_script.exists():
        print(f"❌ 找不到API脚本: {api_script}")
        return None
    
    try:
        # 启动API服务（后台运行）
        process = subprocess.Popen([
            sys.executable, str(api_script)
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        # 等待服务启动
        print("⏳ 等待服务启动...")
        time.sleep(10)
        
        # 检查服务是否启动成功
        try:
            response = requests.get("http://localhost:8000/health", timeout=5)
            if response.status_code == 200:
                health_data = response.json()
                print("✅ 翻译API服务启动成功!")
                print(f"   - 模型已加载: {health_data.get('model_loaded', False)}")
                print(f"   - GPU可用: {health_data.get('gpu_available', False)}")
                return process
            else:
                print(f"❌ 服务健康检查失败: {response.status_code}")
                return None
        except requests.exceptions.RequestException as e:
            print(f"❌ 无法连接到服务: {e}")
            return None
            
    except Exception as e:
        print(f"❌ 启动服务失败: {e}")
        return None

def test_translation_api():
    """测试翻译API"""
    print("\n🧪 测试翻译API...")
    
    test_cases = [
        "炉膛内壁温度",
        "辐射管表面温度", 
        "喷淋水流量",
        "燃气压力调节阀",
        "助燃空气流量计"
    ]
    
    for i, text in enumerate(test_cases, 1):
        try:
            payload = {
                "text": text,
                "from_lang": "zh",
                "to_lang": "en"
            }
            
            response = requests.post(
                "http://localhost:8000/translate", 
                json=payload, 
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                print(f"  {i}. {text}")
                print(f"     翻译: {result['translated_text']}")
                print(f"     简化: {result['simplified_name']}")
            else:
                print(f"  {i}. {text} -> 翻译失败: {response.status_code}")
                
        except Exception as e:
            print(f"  {i}. {text} -> 错误: {e}")

def test_plc_processor():
    """测试PLC数据处理脚本"""
    print("\n📊 测试PLC数据处理...")
    script_dir = Path(__file__).parent
    processor_script = script_dir / "plc_data_processor.py"
    
    if not processor_script.exists():
        print(f"❌ 找不到处理脚本: {processor_script}")
        return
    
    try:
        # 运行PLC数据处理脚本
        result = subprocess.run([
            sys.executable, str(processor_script)
        ], capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0:
            print("✅ PLC数据处理完成")
            print("输出:")
            print(result.stdout)
        else:
            print("❌ PLC数据处理失败")
            print("错误:")
            print(result.stderr)
            
    except subprocess.TimeoutExpired:
        print("⏰ PLC数据处理超时")
    except Exception as e:
        print(f"❌ 执行失败: {e}")

def main():
    """主函数"""
    print("=== PLC翻译系统启动测试 ===\n")
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 启动API服务
    api_process = start_api_server()
    if not api_process:
        print("❌ 无法启动翻译API服务")
        return
    
    try:
        # 测试翻译API
        test_translation_api()
        
        # 询问是否测试PLC处理
        user_input = input("\n是否测试PLC数据处理? (y/n): ").strip().lower()
        if user_input in ['y', 'yes', '是']:
            test_plc_processor()
        
        print("\n🎉 测试完成!")
        print("💡 翻译API服务地址: http://localhost:8000")
        print("📖 API文档地址: http://localhost:8000/docs")
        
        # 询问是否保持服务运行
        user_input = input("\n是否保持翻译API服务运行? (y/n): ").strip().lower()
        if user_input in ['y', 'yes', '是']:
            print("🔄 翻译API服务将继续运行...")
            print("   要停止服务，请按 Ctrl+C")
            try:
                api_process.wait()
            except KeyboardInterrupt:
                print("\n🛑 正在停止服务...")
        
    finally:
        # 清理进程
        if api_process:
            try:
                api_process.terminate()
                api_process.wait(timeout=5)
                print("✅ 翻译API服务已停止")
            except:
                api_process.kill()
                print("🔥 强制停止翻译API服务")

if __name__ == "__main__":
    main()